package com.knshare.utils.Executor;

import java.util.concurrent.*;

/**
 * 线程池基础工具
 * @author rongxun.wu01
 * @product IntelliJ IDEA
 * @project KnShare
 * @Date 2023-05-06 14:10
 */
public class PoolTaskExecutor{
    /**
     * 核心线程数
     */
    private int corePoolSize;
    /**
     * 最大线程数
     */
    private int maxPoolSize;
    /**
     * 空闲时间
     */
    private long keepAliveTime;

    /**
     * 队列类型
     */
    private BlockingQueue<Runnable> workQueue;

    /**
     * 线程工厂
     */
    private ThreadFactory threadFactory;
    /**
     * 拒绝策略
     */
    private RejectedExecutionHandler handler;

    private Boolean allowCoreThreadTimeOut;


    /**
     * 时间单位
     */
    private TimeUnit unit;
    public PoolTaskExecutor(){
        this.keepAliveTime = TimeUnit.SECONDS.toNanos(60L);

    }

    public PoolTaskExecutor setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
        return this;
    }

    public PoolTaskExecutor setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
        return this;
    }

    public PoolTaskExecutor setKeepAliveTime(long keepAliveTime) {
        if (null!=this.unit){
            this.keepAliveTime = this.unit.toNanos(keepAliveTime);
        }else {
            this.keepAliveTime = TimeUnit.SECONDS.toNanos(keepAliveTime);
        }
        return this;
    }

    public PoolTaskExecutor setUnit(TimeUnit unit) {
        this.unit = unit;
        return this;
    }

    public PoolTaskExecutor setWorkQueue(BlockingQueue<Runnable> workQueue) {
        this.workQueue = workQueue;
        return this;
    }

    public PoolTaskExecutor setThreadFactory(ThreadFactory threadFactory) {
        this.threadFactory = threadFactory;
        return this;
    }

    public PoolTaskExecutor setHandler(RejectedExecutionHandler handler) {
        this.handler = handler;
        return this;
    }
    public PoolTaskExecutor setAllowCoreThreadTimeOut(Boolean allowCoreThreadTimeOut) {
        this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
        return this;
    }

    public static PoolTaskExecutor create() {
        return new PoolTaskExecutor();
    }


    public ThreadPoolExecutorService CratePoolTaskExecutor(){
        int corePoolSize = this.corePoolSize;
        int maxPoolSize = this.maxPoolSize;
        long keepAliveTime = this.keepAliveTime;
        Object workQueue;
        //判断线程队列是否设置
        if (null != this.workQueue) {
            workQueue = this.workQueue;
        } else {
            workQueue = corePoolSize <= 0 ? new SynchronousQueue() : new LinkedBlockingDeque(1024);
        }
        if (workQueue instanceof SynchronousQueue){
            maxPoolSize=Integer.MAX_VALUE;
        }

        ThreadFactory threadFactory = (null != this.threadFactory ? this.threadFactory : new ThreadFactoryDefault("defaultThreadFactory"));
        RejectedExecutionHandler handler = (null!=this.handler?this.handler:new  ThreadPoolExecutor.CallerRunsPolicy());
        if (corePoolSize < 0 ||
                maxPoolSize  <= 0 ||
                maxPoolSize < corePoolSize ||
                keepAliveTime < 0){
            throw new IllegalArgumentException();
        }
        if (workQueue == null || threadFactory == null || handler == null){
            throw new NullPointerException();
        }
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.NANOSECONDS, (BlockingQueue)workQueue, threadFactory, handler);
        //allowCoreThreadTimeOut为true
        //该值为true，则线程池数量最后销毁到0个。
        //allowCoreThreadTimeOut为false
        //销毁机制：超过核心线程数时，而且（超过最大值或者timeout过），就会销毁。
        if (null != this.allowCoreThreadTimeOut) {
            threadPoolExecutor.allowCoreThreadTimeOut(this.allowCoreThreadTimeOut);
        }
        return new ThreadPoolExecutorService(threadPoolExecutor);
    }


}
